import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import { getLoginUser } from '@/api/userController'
import accessEnum from '@/access/accessEnum'
import ACCESS_ENUM from '@/access/accessEnum'

/**
 * 存储登录用户信息的状态
 */
export const useLoginUserStore = defineStore('loginUser', () => {
  const loginUser = ref<API.LoginUserVO>({
    userName: '未登录',
    userRole: accessEnum.NOT_LOGIN,
  })

  async function fetchLoginUser() {
    try {
      const res = await getLoginUser()
      if (res.data.code === 200 && res.data.data) {
        loginUser.value = res.data.data
        // 立即保存到localStorage
        saveState()
        return true
      } else {
        // 用户未登录是正常情况，不需要抛出错误
        loginUser.value = {
          userName: '未登录',
          userRole: accessEnum.NOT_LOGIN,
        }
        return false
      }
    } catch {
      // 获取用户信息失败，保持未登录状态
      loginUser.value = {
        userName: '未登录',
        userRole: accessEnum.NOT_LOGIN,
      }
      return false
    }
  }

  /**
   * 设置登录用户
   * @param newLoginUser
   */
  function setLoginUser(newLoginUser: API.LoginUserVO) {
    loginUser.value = newLoginUser
    // 立即保存到本地存储
    saveState()
  }

  const saveState = () => {
    localStorage.setItem('loginUser', JSON.stringify(loginUser.value))
  }

  const loadState = () => {
    try {
      const saved = localStorage.getItem('loginUser')
      if (saved) {
        const parsedUser = JSON.parse(saved)
        // 只有当用户确实已登录时才恢复状态
        if (parsedUser.userRole !== ACCESS_ENUM.NOT_LOGIN) {
          loginUser.value = parsedUser
        }
      }
    } catch {
      // 忽略恢复失败的情况
    }
  }

  const clearState = () => {
    loginUser.value = {
      userAccount: '未登录',
      userRole: ACCESS_ENUM.NOT_LOGIN,
    }
    localStorage.removeItem('loginUser')
  }

  // 初始化时尝试恢复状态
  loadState()

  // 监听状态变化并保存
  watch(
    () => loginUser.value,
    () => saveState(),
    { deep: true },
  )

  // 返回
  return { loginUser, fetchLoginUser, setLoginUser, saveState, loadState, clearState }
})
